% ## Copyright (C) 2014 Santiago
% ## 
% ## This program is free software; you can redistribute it and/or modify it
% ## under the terms of the GNU General Public License as published by
% ## the Free Software Foundation; either version 3 of the License, or
% ## (at your option) any later version.
% ## 
% ## This program is distributed in the hope that it will be useful,
% ## but WITHOUT ANY WARRANTY; without even the implied warranty of
% ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% ## GNU General Public License for more details.
% ## 
% ## You should have received a copy of the GNU General Public License
% ## along with this program.  If not, see <http://www.gnu.org/licenses/>.
% 
% ## -*- texinfo -*- 
% ## @deftypefn {Function File} {@var{retval} =} interactiveRlocus (@var{input1}, @var{input2})
% ##
% ## @seealso{}
% ## @end deftypefn
% 
% ## Author: Santiago <santiago@santiago-nc6400>
% ## Created: 2014-04-14

function [retval] = interactiveRlocus (num, den)
  sys = tf(num, den);
  rlocus(sys);
  locFigure = figure(1);
  locAxis = gca();
  set (locFigure, 'WindowButtonDownFcn', {@onButtonDown, locAxis, sys});
  
end

function onButtonDown(src, evt, locAxis, sys)
  pt = get (locAxis, 'CurrentPoint');
  pt = pt(1,1:2);
  [zeros, poles] = pzmap(sys);
  poles = transpose(poles);
  for pol = poles
    if (abs(pt(1)-pol) < 0.02)
      printf('pole selected\n')
      poles = poles(abs(poles - pol) > 0.02)
      set (src, 'WindowButtonMotionFcn', {@onButtonMotion, locAxis, zeros, poles});
      set (src, 'WindowButtonUpFcn', @onButtonUp)
      break
    end
  end
  
end

function onButtonMotion(src, evt, locAxis, fixzeros, fixpoles)
  printf('moving pole\n')
  pt = get (locAxis, 'CurrentPoint');
  pt = pt(1,1:2)
  rlocus(zpk(fixzeros, [fixpoles, pt(1)], 1)); 
  drawnow;
end
 
 function onButtonUp(src, evt)
  set(src, 'WindowButtonMotionFcn', [])
  set (src, 'WindowButtonMotionFcn', [])
 end